﻿using MultiDAQ_Analysis.License;
using QLicense;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LicenseManager = MultiDAQ_Analysis.License.LicenseManager;

namespace MultiDAQ_Analysis.View
{
    public partial class LicenseViewForm : Form
    {
        private Label lblTitle;
        private GroupBox groupBoxLicenseInfo;
        private GroupBox groupBoxDeviceInfo;
        private GroupBox groupBoxLicenseStatus;

        // 许可证信息控件
        private Label lblLicenseType;
        private Label lblLicenseTypeValue;
        private Label lblIssueDate;
        private Label lblIssueDateValue;
        private Label lblExpireDate;
        private Label lblExpireDateValue;
        private Label lblRemainingDays;
        private Label lblRemainingDaysValue;
        private Label lblLicenseFeatures;
        private TextBox txtLicenseFeatures;

        // 设备信息控件
        private Label lblDeviceUID;
        private TextBox txtDeviceUID;
        private Button btnCopyUID;
        private Label lblMachineName;
        private Label lblMachineNameValue;
        private Label lblUserName;
        private Label lblUserNameValue;

        // 状态信息控件
        private Label lblCurrentStatus;
        private Label lblCurrentStatusValue;
        private PictureBox picStatusIcon;
        private Label lblLastCheck;
        private Label lblLastCheckValue;

        // 操作按钮
        private Button btnReactivate;
        private Button btnExportInfo;
        private Button btnRefresh;
        private Button btnClose;

        // 状态栏
        private StatusStrip statusStrip;
        private ToolStripStatusLabel toolStripStatusLabel;

        public LicenseViewForm()
        {
            InitializeComponent();
            LoadLicenseInfo();
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();

            // Form 设置
            this.ClientSize = new Size(700, 600);
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.StartPosition = FormStartPosition.CenterParent;
            this.Text = "软件授权信息";
            this.ShowIcon = false;
            this.BackColor = SystemColors.Control;

            // 标题
            lblTitle = new Label()
            {
                Text = "软件许可证信息查看",
                Location = new Point(20, 20),
                Size = new Size(660, 25),
                Font = new Font("Microsoft YaHei", 12F, FontStyle.Bold),
                ForeColor = Color.FromArgb(64, 64, 64),
                TextAlign = ContentAlignment.MiddleCenter
            };

            // 许可证状态分组框
            groupBoxLicenseStatus = new GroupBox()
            {
                Text = "许可证状态",
                Location = new Point(20, 55),
                Size = new Size(660, 80),
                Font = new Font("Microsoft YaHei", 9F)
            };

            // 状态图标
            picStatusIcon = new PictureBox()
            {
                Location = new Point(20, 25),
                Size = new Size(32, 32),
                SizeMode = PictureBoxSizeMode.StretchImage
            };

            // 当前状态
            lblCurrentStatus = new Label()
            {
                Text = "当前状态:",
                Location = new Point(65, 25),
                Size = new Size(80, 20),
                Font = new Font("Microsoft YaHei", 9F)
            };

            lblCurrentStatusValue = new Label()
            {
                Text = "检查中...",
                Location = new Point(150, 25),
                Size = new Size(200, 20),
                Font = new Font("Microsoft YaHei", 9F, FontStyle.Bold)
            };

            // 最后检查时间
            lblLastCheck = new Label()
            {
                Text = "最后检查:",
                Location = new Point(65, 50),
                Size = new Size(80, 20),
                Font = new Font("Microsoft YaHei", 9F)
            };

            lblLastCheckValue = new Label()
            {
                Text = "-",
                Location = new Point(150, 50),
                Size = new Size(200, 20),
                Font = new Font("Microsoft YaHei", 9F)
            };

            // 许可证信息分组框
            groupBoxLicenseInfo = new GroupBox()
            {
                Text = "许可证详细信息",
                Location = new Point(20, 145),
                Size = new Size(660, 220),
                Font = new Font("Microsoft YaHei", 9F)
            };

            // 许可证类型
            lblLicenseType = new Label()
            {
                Text = "许可证类型:",
                Location = new Point(20, 30),
                Size = new Size(100, 20),
                Font = new Font("Microsoft YaHei", 9F)
            };

            lblLicenseTypeValue = new Label()
            {
                Text = "-",
                Location = new Point(130, 30),
                Size = new Size(200, 20),
                Font = new Font("Microsoft YaHei", 9F, FontStyle.Bold)
            };

            // 发放日期
            lblIssueDate = new Label()
            {
                Text = "发放日期:",
                Location = new Point(350, 30),
                Size = new Size(100, 20),
                Font = new Font("Microsoft YaHei", 9F)
            };

            lblIssueDateValue = new Label()
            {
                Text = "-",
                Location = new Point(460, 30),
                Size = new Size(180, 20),
                Font = new Font("Microsoft YaHei", 9F)
            };

            // 到期日期
            lblExpireDate = new Label()
            {
                Text = "到期日期:",
                Location = new Point(20, 60),
                Size = new Size(100, 20),
                Font = new Font("Microsoft YaHei", 9F)
            };

            lblExpireDateValue = new Label()
            {
                Text = "-",
                Location = new Point(130, 60),
                Size = new Size(200, 20),
                Font = new Font("Microsoft YaHei", 9F, FontStyle.Bold)
            };

            // 剩余天数
            lblRemainingDays = new Label()
            {
                Text = "剩余天数:",
                Location = new Point(350, 60),
                Size = new Size(100, 20),
                Font = new Font("Microsoft YaHei", 9F)
            };

            lblRemainingDaysValue = new Label()
            {
                Text = "-",
                Location = new Point(460, 60),
                Size = new Size(180, 20),
                Font = new Font("Microsoft YaHei", 9F, FontStyle.Bold)
            };

            // 授权功能
            lblLicenseFeatures = new Label()
            {
                Text = "授权功能:",
                Location = new Point(20, 90),
                Size = new Size(100, 20),
                Font = new Font("Microsoft YaHei", 9F)
            };

            txtLicenseFeatures = new TextBox()
            {
                Location = new Point(20, 115),
                Size = new Size(620, 85),
                Font = new Font("Microsoft YaHei", 9F),
                Multiline = true,
                ReadOnly = true,
                ScrollBars = ScrollBars.Vertical,
                BackColor = SystemColors.Control,
                BorderStyle = BorderStyle.FixedSingle,
                Text = "正在加载功能列表..."
            };

            // 设备信息分组框
            groupBoxDeviceInfo = new GroupBox()
            {
                Text = "设备信息",
                Location = new Point(20, 375),
                Size = new Size(660, 110),
                Font = new Font("Microsoft YaHei", 9F)
            };

            // 设备标识
            lblDeviceUID = new Label()
            {
                Text = "设备标识:",
                Location = new Point(20, 30),
                Size = new Size(80, 20),
                Font = new Font("Microsoft YaHei", 9F)
            };

            txtDeviceUID = new TextBox()
            {
                Location = new Point(105, 28),
                Size = new Size(450, 23),
                Font = new Font("Consolas", 9F),
                ReadOnly = true,
                BackColor = SystemColors.Control,
                BorderStyle = BorderStyle.FixedSingle
            };

            btnCopyUID = new Button()
            {
                Text = "复制",
                Location = new Point(565, 27),
                Size = new Size(70, 25),
                Font = new Font("Microsoft YaHei", 8F),
                UseVisualStyleBackColor = true
            };
            btnCopyUID.Click += BtnCopyUID_Click;

            // 计算机名
            lblMachineName = new Label()
            {
                Text = "计算机名:",
                Location = new Point(20, 60),
                Size = new Size(80, 20),
                Font = new Font("Microsoft YaHei", 9F)
            };

            lblMachineNameValue = new Label()
            {
                Text = Environment.MachineName,
                Location = new Point(105, 60),
                Size = new Size(200, 20),
                Font = new Font("Microsoft YaHei", 9F)
            };

            // 用户名
            lblUserName = new Label()
            {
                Text = "用户名:",
                Location = new Point(350, 60),
                Size = new Size(80, 20),
                Font = new Font("Microsoft YaHei", 9F)
            };

            lblUserNameValue = new Label()
            {
                Text = Environment.UserName,
                Location = new Point(430, 60),
                Size = new Size(200, 20),
                Font = new Font("Microsoft YaHei", 9F)
            };

            // 操作按钮
            btnRefresh = new Button()
            {
                Text = "刷新",
                Location = new Point(350, 510),
                Size = new Size(80, 35),
                Font = new Font("Microsoft YaHei", 9F),
                UseVisualStyleBackColor = true,
                FlatStyle = FlatStyle.System
            };
            btnRefresh.Click += BtnRefresh_Click;

            btnReactivate = new Button()
            {
                Text = "重新激活",
                Location = new Point(440, 510),
                Size = new Size(100, 35),
                Font = new Font("Microsoft YaHei", 9F),
                UseVisualStyleBackColor = true,
                FlatStyle = FlatStyle.System
            };
            btnReactivate.Click += BtnReactivate_Click;

            btnExportInfo = new Button()
            {
                Text = "导出信息",
                Location = new Point(550, 510),
                Size = new Size(80, 35),
                Font = new Font("Microsoft YaHei", 9F),
                UseVisualStyleBackColor = true,
                FlatStyle = FlatStyle.System
            };
            btnExportInfo.Click += BtnExportInfo_Click;

            btnClose = new Button()
            {
                Text = "关闭",
                Location = new Point(640, 510),
                Size = new Size(60, 35),
                Font = new Font("Microsoft YaHei", 9F),
                UseVisualStyleBackColor = true,
                DialogResult = DialogResult.OK,
                FlatStyle = FlatStyle.System
            };

            // 状态栏
            statusStrip = new StatusStrip();
            toolStripStatusLabel = new ToolStripStatusLabel("就绪");
            statusStrip.Items.Add(toolStripStatusLabel);

            // 添加控件到分组框
            groupBoxLicenseStatus.Controls.AddRange(new Control[] {
                picStatusIcon, lblCurrentStatus, lblCurrentStatusValue,
                lblLastCheck, lblLastCheckValue
            });

            groupBoxLicenseInfo.Controls.AddRange(new Control[] {
                lblLicenseType, lblLicenseTypeValue,
                lblIssueDate, lblIssueDateValue,
                lblExpireDate, lblExpireDateValue,
                lblRemainingDays, lblRemainingDaysValue,
                lblLicenseFeatures, txtLicenseFeatures
            });

            groupBoxDeviceInfo.Controls.AddRange(new Control[] {
                lblDeviceUID, txtDeviceUID, btnCopyUID,
                lblMachineName, lblMachineNameValue,
                lblUserName, lblUserNameValue
            });

            // 添加控件到窗体
            this.Controls.AddRange(new Control[] {
                lblTitle,
                groupBoxLicenseStatus,
                groupBoxLicenseInfo,
                groupBoxDeviceInfo,
                btnRefresh,
                btnReactivate,
                btnExportInfo,
                btnClose,
                statusStrip
            });

            // 设置默认按钮
            this.AcceptButton = btnClose;

            // 设置Tab顺序
            btnRefresh.TabIndex = 0;
            btnReactivate.TabIndex = 1;
            btnExportInfo.TabIndex = 2;
            btnClose.TabIndex = 3;

            this.ResumeLayout(false);
            this.PerformLayout();
        }

        /// <summary>
        /// 加载许可证信息
        /// </summary>
        private void LoadLicenseInfo()
        {
            try
            {
                toolStripStatusLabel.Text = "正在加载许可证信息...";

                // 获取设备UID
                txtDeviceUID.Text = GetDeviceUID();

                // 检查许可证管理器是否初始化
                if (!LicenseManager.IsInitialized())
                {
                    ShowNotLicensedStatus("许可证管理器未初始化");
                    return;
                }

                // 获取许可证状态
                var licenseStatus = LicenseManager.GetLicenseStatus();
                var licenseInfo = LicenseManager.GetLicenseInfo();

                if (licenseInfo != null && licenseStatus == LicenseStatus.VALID)
                {
                    ShowValidLicenseInfo(licenseInfo);
                }
                else
                {
                    ShowNotLicensedStatus(GetStatusDescription(licenseStatus));
                }

                lblLastCheckValue.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                toolStripStatusLabel.Text = "许可证信息加载完成";
            }
            catch (Exception ex)
            {
                ShowErrorStatus($"加载许可证信息时发生错误: {ex.Message}");
                toolStripStatusLabel.Text = "加载失败";
            }
        }

        /// <summary>
        /// 显示有效许可证信息
        /// </summary>
        private void ShowValidLicenseInfo(dynamic licenseInfo)
        {
            // 设置状态为有效
            lblCurrentStatusValue.Text = "已激活";
            lblCurrentStatusValue.ForeColor = Color.Green;
            SetStatusIcon(true);

            // 设置许可证信息
            lblLicenseTypeValue.Text = GetLicenseTypeDescription(licenseInfo.LicenseType);

            if (licenseInfo.IssueDate != null)
                lblIssueDateValue.Text = licenseInfo.IssueDate.ToString("yyyy-MM-dd");

            if (licenseInfo.ExpireDate != null)
            {
                lblExpireDateValue.Text = licenseInfo.ExpireDate.ToString("yyyy-MM-dd");

                // 计算剩余天数
                TimeSpan remaining = licenseInfo.ExpireDate - DateTime.Now;
                int remainingDays = (int)remaining.TotalDays;

                lblRemainingDaysValue.Text = $"{remainingDays} 天";

                // 根据剩余时间设置颜色
                if (remainingDays < 0)
                {
                    lblRemainingDaysValue.ForeColor = Color.Red;
                    lblExpireDateValue.ForeColor = Color.Red;
                }
                else if (remainingDays < 30)
                {
                    lblRemainingDaysValue.ForeColor = Color.Orange;
                    lblExpireDateValue.ForeColor = Color.Orange;
                }
                else
                {
                    lblRemainingDaysValue.ForeColor = Color.Green;
                    lblExpireDateValue.ForeColor = Color.Green;
                }
            }

            // 显示授权功能
            txtLicenseFeatures.Text = GetLicenseFeaturesDescription(licenseInfo);
        }

        /// <summary>
        /// 显示未授权状态
        /// </summary>
        private void ShowNotLicensedStatus(string reason)
        {
            lblCurrentStatusValue.Text = "未激活";
            lblCurrentStatusValue.ForeColor = Color.Red;
            SetStatusIcon(false);

            lblLicenseTypeValue.Text = "无";
            lblIssueDateValue.Text = "-";
            lblExpireDateValue.Text = "-";
            lblRemainingDaysValue.Text = "-";
            txtLicenseFeatures.Text = $"软件未激活: {reason}";
        }

        /// <summary>
        /// 显示错误状态
        /// </summary>
        private void ShowErrorStatus(string error)
        {
            lblCurrentStatusValue.Text = "检查失败";
            lblCurrentStatusValue.ForeColor = Color.Red;
            SetStatusIcon(false);

            txtLicenseFeatures.Text = error;
        }

        /// <summary>
        /// 设置状态图标
        /// </summary>
        private void SetStatusIcon(bool isValid)
        {
            try
            {
                if (isValid)
                {
                    // 绿色对勾图标 - 创建简单的位图
                    Bitmap icon = new Bitmap(32, 32);
                    using (Graphics g = Graphics.FromImage(icon))
                    {
                        g.Clear(Color.Transparent);
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                        using (Brush brush = new SolidBrush(Color.Green))
                        {
                            g.FillEllipse(brush, 2, 2, 28, 28);
                        }
                        using (Pen pen = new Pen(Color.White, 3))
                        {
                            g.DrawLines(pen, new Point[] {
                                new Point(8, 16),
                                new Point(14, 22),
                                new Point(24, 10)
                            });
                        }
                    }
                    picStatusIcon.Image = icon;
                }
                else
                {
                    // 红色X图标
                    Bitmap icon = new Bitmap(32, 32);
                    using (Graphics g = Graphics.FromImage(icon))
                    {
                        g.Clear(Color.Transparent);
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                        using (Brush brush = new SolidBrush(Color.Red))
                        {
                            g.FillEllipse(brush, 2, 2, 28, 28);
                        }
                        using (Pen pen = new Pen(Color.White, 3))
                        {
                            g.DrawLine(pen, 10, 10, 22, 22);
                            g.DrawLine(pen, 22, 10, 10, 22);
                        }
                    }
                    picStatusIcon.Image = icon;
                }
            }
            catch (Exception ex)
            {
                // 如果创建图标失败，就不显示图标
                Console.WriteLine($"创建状态图标失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取设备UID
        /// </summary>
        private string GetDeviceUID()
        {
            try
            {
                if (LicenseManager.IsInitialized())
                {
                    return LicenseManager.GetDeviceUID();
                }
                else
                {
                    return GenerateBasicDeviceUID();
                }
            }
            catch
            {
                return "获取失败";
            }
        }

        /// <summary>
        /// 生成基本设备UID
        /// </summary>
        private string GenerateBasicDeviceUID()
        {
            try
            {
                string combined = $"{Environment.MachineName}_{Environment.UserName}_{Environment.OSVersion.VersionString}";
                int hash = combined.GetHashCode();
                return $"BASIC_{Math.Abs(hash):X8}";
            }
            catch
            {
                return $"FALLBACK_{DateTime.Now.Ticks:X}";
            }
        }

        /// <summary>
        /// 获取许可证类型描述
        /// </summary>
        private string GetLicenseTypeDescription(object licenseType)
        {
            if (licenseType == null) return "未知";

            // 根据你的LicenseTypes枚举返回描述
            switch (licenseType.ToString())
            {
                case "Single":
                    return "单用户许可证";
                case "Volume":
                    return "批量许可证";
                default:
                    return licenseType.ToString();
            }
        }

        /// <summary>
        /// 获取状态描述
        /// </summary>
        private string GetStatusDescription(LicenseStatus status)
        {
            switch (status)
            {
                case LicenseStatus.VALID:
                    return "许可证有效";
                case LicenseStatus.INVALID:
                    return "许可证无效";
                case LicenseStatus.CRACKED:
                    return "许可证被破解";
                default:
                    return "未知状态";
            }
        }

        /// <summary>
        /// 获取许可证功能描述
        /// </summary>
        private string GetLicenseFeaturesDescription(dynamic licenseInfo)
        {
            var features = new StringBuilder();
            features.AppendLine($"许可证持有人: {licenseInfo.CustomerName ?? "未指定"}");
            features.AppendLine($"许可证ID: {licenseInfo.LicenseId ?? "未指定"}");
            features.AppendLine();
            features.AppendLine("授权功能:");

            // 根据你的实际功能添加
            if (licenseInfo.Features != null)
            {
                foreach (var feature in licenseInfo.Features)
                {
                    features.AppendLine($"• {feature}");
                }
            }
            else
            {
                features.AppendLine("• 基本功能");
                features.AppendLine("• 数据分析");
                features.AppendLine("• 报表生成");
            }

            return features.ToString();
        }

        #region 事件处理

        private void BtnCopyUID_Click(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(txtDeviceUID.Text))
                {
                    Clipboard.SetText(txtDeviceUID.Text);
                    toolStripStatusLabel.Text = "设备标识码已复制到剪贴板";

                    // 2秒后恢复状态文本
                    Timer timer = new Timer { Interval = 2000 };
                    timer.Tick += (s, args) =>
                    {
                        toolStripStatusLabel.Text = "就绪";
                        timer.Stop();
                        timer.Dispose();
                    };
                    timer.Start();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"复制失败: {ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnRefresh_Click(object sender, EventArgs e)
        {
            LoadLicenseInfo();
        }

        private void BtnReactivate_Click(object sender, EventArgs e)
        {
            var result = MessageBox.Show("确定要重新激活软件吗？\n\n这将打开激活对话框。", "确认重新激活",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                try
                {
                    // 打开许可证输入窗体
                    using (var inputForm = new LicenseInputForm())
                    {
                        if (inputForm.ShowDialog() == DialogResult.OK)
                        {
                            // 重新加载许可证信息
                            LoadLicenseInfo();
                            MessageBox.Show("重新激活完成！", "成功",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"重新激活失败: {ex.Message}", "错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void BtnExportInfo_Click(object sender, EventArgs e)
        {
            try
            {
                using (var saveDialog = new SaveFileDialog())
                {
                    saveDialog.Filter = "文本文件|*.txt|所有文件|*.*";
                    saveDialog.FileName = $"LicenseInfo_{DateTime.Now:yyyyMMdd_HHmmss}.txt";

                    if (saveDialog.ShowDialog() == DialogResult.OK)
                    {
                        var info = new StringBuilder();
                        info.AppendLine("软件许可证信息导出");
                        info.AppendLine($"导出时间: {DateTime.Now}");
                        info.AppendLine(new string('=', 50));
                        info.AppendLine();

                        info.AppendLine($"当前状态: {lblCurrentStatusValue.Text}");
                        info.AppendLine($"许可证类型: {lblLicenseTypeValue.Text}");
                        info.AppendLine($"发放日期: {lblIssueDateValue.Text}");
                        info.AppendLine($"到期日期: {lblExpireDateValue.Text}");
                        info.AppendLine($"剩余天数: {lblRemainingDaysValue.Text}");
                        info.AppendLine();

                        info.AppendLine("设备信息:");
                        info.AppendLine($"设备标识: {txtDeviceUID.Text}");
                        info.AppendLine($"计算机名: {lblMachineNameValue.Text}");
                        info.AppendLine($"用户名: {lblUserNameValue.Text}");
                        info.AppendLine();

                        info.AppendLine("授权功能:");
                        info.AppendLine(txtLicenseFeatures.Text);

                        System.IO.File.WriteAllText(saveDialog.FileName, info.ToString(), Encoding.UTF8);

                        MessageBox.Show($"许可证信息已导出到:\n{saveDialog.FileName}", "导出成功",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出失败: {ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            // 设置窗体居中
            this.CenterToParent();
        }
    }
}